package com.model.common.utils.view;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lljjcoder.citypickerview.widget.CanShow;
import com.lljjcoder.citypickerview.widget.wheel.OnWheelChangedListener;
import com.lljjcoder.citypickerview.widget.wheel.WheelView;
import com.model.common.R;
import com.model.common.ui.adapter.city.AreaWheelAdapter;
import com.model.common.ui.adapter.city.CityWheelAdapter;
import com.model.common.ui.adapter.city.ProvinceWheelAdapter;
import com.model.common.utils.model.city.AreaBean;
import com.model.common.utils.model.city.CityBean;
import com.model.common.utils.model.city.ProvinceBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2022/2/22
 * 自定义三级联动选择省市区
 */
public class MyCityPicker implements CanShow, OnWheelChangedListener {

    private final Context context;
    private final PopupWindow popupWindow;
    private final View popView;
    private final WheelView mViewProvince, mViewCity, mViewDistrict;

    /**
     * 所有省
     */
    protected List<ProvinceBean> mProvinceData;

    /**
     * key - 省 value - 市
     */
    protected Map<String, List<CityBean>> mCityDataMap = new HashMap<>();

    /**
     * key - 市 values - 区
     */
    protected Map<String, List<AreaBean>> mDistrictDataMap = new HashMap<>();
    //当前省的名称
    protected String mCurrentProvinceId;
    //当前市的名称
    protected String mCurrentCityId;
    //当前区的名称
    protected String mCurrentDistrictId = "";

    private OnCityItemClickListener listener;

    public interface OnCityItemClickListener {
        void onSelected(int... citySelected);
    }

    public void setOnCityItemClickListener(OnCityItemClickListener listener) {
        this.listener = listener;
    }

    // Text settings
    private final int textColor;
    private final int textSize;
    // 滚轮显示的item个数
    private final int visibleItems;
    //省滚轮是否循环滚动
    private final boolean isProvinceCyclic;
    //市滚轮是否循环滚动
    private final boolean isCityCyclic;
    //区滚轮是否循环滚动
    private final boolean isDistrictCyclic;
    //item间距
    private final int padding;
    //两级联动
    private final boolean showProvinceAndCity;

    private MyCityPicker(Builder builder) {
        this.textColor = builder.textColor;
        this.textSize = builder.textSize;
        this.visibleItems = builder.visibleItems;
        this.isProvinceCyclic = builder.isProvinceCyclic;
        this.isDistrictCyclic = builder.isDistrictCyclic;
        this.isCityCyclic = builder.isCityCyclic;
        this.context = builder.mContext;
        this.padding = builder.padding;
        //标题背景颜色
        String titleBackgroundColorStr = builder.titleBackgroundColorStr;
        String confirmTextColorStr = builder.confirmTextColorStr;
        String cancelTextColorStr = builder.cancelTextColorStr;

        this.showProvinceAndCity = builder.showProvinceAndCity;

        LayoutInflater layoutInflater = LayoutInflater.from(context);
        popView = layoutInflater.inflate(R.layout.pop_my_citypicker, null);

        mViewProvince = popView.findViewById(com.lljjcoder.citypickerview.R.id.id_province);
        mViewCity = popView.findViewById(com.lljjcoder.citypickerview.R.id.id_city);
        mViewDistrict = popView.findViewById(com.lljjcoder.citypickerview.R.id.id_district);
        RelativeLayout mRelativeTitleBg = popView.findViewById(com.lljjcoder.citypickerview.R.id.rl_title);
        TextView mTvOK = popView.findViewById(com.lljjcoder.citypickerview.R.id.tv_confirm);
        TextView mTvTitle = popView.findViewById(com.lljjcoder.citypickerview.R.id.tv_title);
        TextView mTvCancel = popView.findViewById(com.lljjcoder.citypickerview.R.id.tv_cancel);


        popupWindow = new PopupWindow(popView, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x80000000));
        popupWindow.setAnimationStyle(com.lljjcoder.citypickerview.R.style.AnimBottom);
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);


        //设置标题背景颜色
        if (!TextUtils.isEmpty(titleBackgroundColorStr)) {
            mRelativeTitleBg.setBackgroundColor(Color.parseColor(titleBackgroundColorStr));
        }

        //设置标题
        String mTitle = "";
        if (!TextUtils.isEmpty(mTitle)) {
            mTvTitle.setText(mTitle);
        }

        //设置确认按钮文字颜色
        if (!TextUtils.isEmpty(confirmTextColorStr)) {
            mTvOK.setTextColor(Color.parseColor(confirmTextColorStr));
        }

        //设置取消按钮文字颜色
        if (!TextUtils.isEmpty(cancelTextColorStr)) {
            mTvCancel.setTextColor(Color.parseColor(cancelTextColorStr));
        }

        //只显示省市两级联动
        if (this.showProvinceAndCity) {
            mViewDistrict.setVisibility(View.GONE);
        } else {
            mViewDistrict.setVisibility(View.VISIBLE);
        }
        // 添加change事件
        mViewProvince.addChangingListener(this);
        // 添加change事件
        mViewCity.addChangingListener(this);
        // 添加change事件
        mViewDistrict.addChangingListener(this);
        // 添加onclick事件
        mTvCancel.setOnClickListener(v -> hide());
        mTvOK.setOnClickListener(v -> {
            try {
                if (showProvinceAndCity) {
                    listener.onSelected(mViewProvince.getCurrentItem(),
                            mViewCity.getCurrentItem(), 0);
                } else {
                    listener.onSelected(mViewProvince.getCurrentItem(), mViewCity.getCurrentItem(),
                            mViewDistrict.getCurrentItem());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            hide();
        });

    }

    public static class Builder {
        /**
         * Default text color
         */
        public static final int DEFAULT_TEXT_COLOR = 0xFF585858;

        /**
         * Default text size
         */
        public static final int DEFAULT_TEXT_SIZE = 18;

        // Text settings
        private int textColor = DEFAULT_TEXT_COLOR;

        private int textSize = DEFAULT_TEXT_SIZE;

        /**
         * 滚轮显示的item个数
         */
        private static final int DEF_VISIBLE_ITEMS = 5;

        // Count of visible items
        private int visibleItems = DEF_VISIBLE_ITEMS;

        /**
         * 省滚轮是否循环滚动
         */
        private boolean isProvinceCyclic = false;

        /**
         * 市滚轮是否循环滚动
         */
        private boolean isCityCyclic = true;

        /**
         * 区滚轮是否循环滚动
         */
        private boolean isDistrictCyclic = true;

        private final Context mContext;

        /**
         * item间距
         */
        private int padding = 5;


        /**
         * Color.BLACK
         */
        private String cancelTextColorStr = "#000000";


        /**
         * Color.BLUE
         */
        private String confirmTextColorStr = "#0000FF";

        /**
         * 标题背景颜色
         */
        private String titleBackgroundColorStr = "#E9E9E9";

        /**
         * 两级联动
         */
        private boolean showProvinceAndCity = false;

        public Builder(Context context) {
            this.mContext = context;
        }

        /**
         * 设置标题背景颜色
         *
         * @param colorBg 背景颜色
         */
        public Builder titleBackgroundColor(String colorBg) {
            this.titleBackgroundColorStr = colorBg;
            return this;
        }

        /**
         * 设置标题
         */
        public Builder title(String mTitle) {
            return this;
        }

        /**
         * 是否只显示省市两级联动
         */
        public Builder onlyShowProvinceAndCity(boolean flag) {
            this.showProvinceAndCity = flag;
            return this;
        }

        /**
         * 确认按钮文字颜色
         */
        public Builder confirTextColor(String color) {
            this.confirmTextColorStr = color;
            return this;
        }

        /**
         * 取消按钮文字颜色
         */
        public Builder cancelTextColor(String color) {
            this.cancelTextColorStr = color;
            return this;
        }

        /**
         * item文字颜色
         */
        public Builder textColor(int textColor) {
            this.textColor = textColor;
            return this;
        }

        /**
         * item文字大小
         */
        public Builder textSize(int textSize) {
            this.textSize = textSize;
            return this;
        }

        /**
         * 滚轮显示的item个数
         */
        public Builder visibleItemsCount(int visibleItems) {
            this.visibleItems = visibleItems;
            return this;
        }

        /**
         * 省滚轮是否循环滚动
         */
        public Builder provinceCyclic(boolean isProvinceCyclic) {
            this.isProvinceCyclic = isProvinceCyclic;
            return this;
        }

        /**
         * 市滚轮是否循环滚动
         */
        public Builder cityCyclic(boolean isCityCyclic) {
            this.isCityCyclic = isCityCyclic;
            return this;
        }

        /**
         * 区滚轮是否循环滚动
         */
        public Builder districtCyclic(boolean isDistrictCyclic) {
            this.isDistrictCyclic = isDistrictCyclic;
            return this;
        }

        /**
         * item间距
         */
        public Builder itemPadding(int itemPadding) {
            this.padding = itemPadding;
            return this;
        }

        public MyCityPicker build() {
            return new MyCityPicker(this);
        }

    }

    private void setUpData() {
        ProvinceWheelAdapter arrayWheelAdapter = new ProvinceWheelAdapter(context, mProvinceData);
        mViewProvince.setViewAdapter(arrayWheelAdapter);
        //获取所设置的省的位置，直接定位到该位置
        mViewProvince.setCurrentItem(0);
        // 设置可见条目数量
        mViewProvince.setVisibleItems(visibleItems);
        mViewCity.setVisibleItems(visibleItems);
        mViewDistrict.setVisibleItems(visibleItems);
        mViewProvince.setCyclic(isProvinceCyclic);
        mViewCity.setCyclic(isCityCyclic);
        mViewDistrict.setCyclic(isDistrictCyclic);
        arrayWheelAdapter.setPadding(padding);
        arrayWheelAdapter.setTextColor(textColor);
        arrayWheelAdapter.setTextSize(textSize);

        updateCities();
        updateAreas();
    }

    public List<ProvinceBean> getProvinceData() {
        return mProvinceData;
    }

    public Map<String, List<CityBean>> getCityDataMap() {
        return mCityDataMap;
    }

    public Map<String, List<AreaBean>> getDistrictDataMap() {
        return mDistrictDataMap;
    }

    public void setProvinceData(List<ProvinceBean> mProvinceData) {
        this.mProvinceData = mProvinceData;
    }

    public void setCityDataMap(Map<String, List<CityBean>> mCityDataMap) {
        this.mCityDataMap = mCityDataMap;
    }

    public void setDistrictDataMap(Map<String, List<AreaBean>> mDistrictDataMap) {
        this.mDistrictDataMap = mDistrictDataMap;
    }

    /**
     * 根据当前的市，更新区WheelView的信息
     */
    private void updateAreas() {
        int pCurrent = mViewCity.getCurrentItem();
        try {
            mCurrentCityId = mCityDataMap.get(mCurrentProvinceId).get(pCurrent).getValue();
        } catch (Exception e) {
            e.printStackTrace();
            mCurrentCityId = "";
        }
        List<AreaBean> areas = mDistrictDataMap.get(mCurrentCityId);

        if (areas == null) {
            areas = new ArrayList<>();
        }

        AreaWheelAdapter districtWheel = new AreaWheelAdapter(context, areas);
        // 设置可见条目数量
        districtWheel.setTextColor(textColor);
        districtWheel.setTextSize(textSize);
        mViewDistrict.setViewAdapter(districtWheel);
        mViewDistrict.setCurrentItem(0);
        //获取第一个区名称
        try {
            mCurrentDistrictId = mDistrictDataMap.get(mCurrentCityId).get(0).getValue();
        } catch (Exception e) {
            e.printStackTrace();
            mCurrentDistrictId = "";
        }
        districtWheel.setPadding(padding);
    }

    /**
     * 根据当前的省，更新市WheelView的信息
     */
    private void updateCities() {
        int pCurrent = mViewProvince.getCurrentItem();
        mCurrentProvinceId = mProvinceData.get(pCurrent).getValue();
        List<CityBean> cities = mCityDataMap.get(mCurrentProvinceId);
        if (cities == null) {
            cities = new ArrayList<>();
        }

        CityWheelAdapter cityWheel = new CityWheelAdapter(context, cities);
        // 设置可见条目数量
        cityWheel.setTextColor(textColor);
        cityWheel.setTextSize(textSize);
        mViewCity.setViewAdapter(cityWheel);
        mViewCity.setCurrentItem(0);
        cityWheel.setPadding(padding);
        updateAreas();
    }

    @Override
    public void setType(int type) {
    }

    @Override
    public void show() {
        if (!isShow()) {
            setUpData();
            popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 0);
        }
    }

    @Override
    public void hide() {
        if (isShow()) {
            popupWindow.dismiss();
        }
    }

    @Override
    public boolean isShow() {
        return popupWindow.isShowing();
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        if (wheel == mViewProvince) {
            updateCities();
        } else if (wheel == mViewCity) {
            updateAreas();
        } else if (wheel == mViewDistrict) {
            mCurrentDistrictId = mDistrictDataMap.get(mCurrentCityId).get(newValue).getValue();
        }
    }
}
